import { useState, useEffect } from 'react';
import { Button, message } from 'antd';
import { FormPro } from '@/components';
import { FormInstance } from 'antd/lib/form';
import React, { useRef, useCallback } from 'react';
import { FormItem } from '@/components/FormPro/types';
import serviceAgreement from '@/service/serviceAgreement';
import getDetail from '@/service/serviceAgreement/getDetail';
import styles from './styles.less';

const Settings = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const formRef = useRef<FormInstance>();
  const onSubmit = useCallback(async () => {
    const fields = await formRef.current?.validateFields();
    setLoading(true);
    try {
      await serviceAgreement(fields);
      message.success('保存成功');
    } catch (e) {
      message.error('保存失败');
    }
    setLoading(false);
  }, []);

  const fetchDetail = useCallback(() => {
    getDetail().then((res: any) => {
      formRef.current?.setFieldsValue({
        serviceAgreement: res?.value
      });
    });
  }, []);


  useEffect(() => {
    fetchDetail();
  }, [fetchDetail]);

  const formList: FormItem[] = [
    {
      type: 'editor',
      name: 'serviceAgreement',
      label: '服务协议',
      rules: [{
        required: true,
        message: '请输入服务协议',
      }],
    },
  ];

  return (
    <div className={styles.container}>
      <FormPro
        formList={formList}
        ref={(e: FormInstance) => formRef.current = e}
      />
      <div className={styles.footer}>
        <Button type="primary" onClick={onSubmit} loading={loading}>
          保存
        </Button>
      </div>
    </div>
  );
};

export default Settings;
